import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken,setToken } from '@/utils/auth' // get token from cookie
// import { getToken,getTokenWX } from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login','/loginwait'] // no redirect whitelist
// const whiteList = [‘/login’, ‘/auth-redirect’, ‘/bind’, ‘/register’, ‘/register1’, ‘/agreement1’, ‘/serve’,‘/backindex’,‘/pdf’,‘/white’]
const test = false;
router.beforeEach(async(to, from, next) => {
  if (test) return next();
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)
  // console.log('111',localStorage.getItem('token'));
  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {

    // if (to.path === '/login' ||to.path==='/login?token=eyJKV1QiOiJKV1QiLCJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NjYsImlhdCI6MTY2NTIwOTUyOCwianRpIjoiNzc2YmEyMzNlMWRhNDQzNmE2MzU3NWIzMGJiYjkxY2EifQ._BYGopKDKYbfhNnY0wy4Ud7e01HrvSBgjRZ3p4C2eyY')
    // if(to.path === `/login?token=${hasToken}`)
    // {
    //   console.log('success');
    //   next({ path: '/dashboard' })
    //   NProgress.done()
    //   console.log('success');
    // }
    // else {
      // if(to.path ==="/login?token="){
      //   next({path:'/dash'})
      // }
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      }
      //一直判断else
      else {
        try {
          // get user info
          await store.dispatch('user/getInfo')

          next()
        } catch (error) {
          Message.error(error || 'Has Error')
          next()
        }
      }
      console.log("拿到token啦");
      console.log("zsj",hasToken);
    // }
  }
  //如果没有拿到token
  else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      //// 在免登录白名单，直接进入,这里我们设置的白名单只有login
      next()
      console.log('123456');
    }
    // 否则全部重定向到登录页
    else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
    next()
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
